package com.yuan.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {


    @PostMapping("/upload")
    @ResponseBody
    public String upload(
            @RequestParam("username") String username,
            @RequestParam("headImg") MultipartFile headImg,
            @RequestParam(value = "lifeImg",required = false) MultipartFile[]  lifeImg

    ) throws IOException {
        String originalFilename = headImg.getOriginalFilename();
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + suffix;
        File classPath = ResourceUtils.getFile("classpath:static/");// 获取静态资源目录
        File dir = new File(classPath, "upload");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        headImg.transferTo(new File(dir, newFileName));
        return "success";
    }



    @GetMapping("/filedownload")
    public ResponseEntity<byte[]> filedownload(
            @RequestParam("fileName")   String fileName
    ) throws IOException {
        File file = ResourceUtils.getFile("classpath:static/files/" + fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);

        // ①创建MultiValueMap接口类型的对象，实现类是HttpHeaders
        MultiValueMap<String, String> responseHeaderMap = new HttpHeaders();
        responseHeaderMap.add("Content-Disposition", "attachment; filename="+fileName);
        ResponseEntity responseEntity = new ResponseEntity(bytes,responseHeaderMap, HttpStatus.OK);


        return responseEntity;
    }

}
